package com.learnaop.javaaop.example.baseProxy.a03CglibProxy;

import com.learnaop.javaaop.example.baseProxy.service.impl.BaseProxyUsedServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibSomeServiceProxy implements MethodInterceptor {

    private BaseProxyUsedServiceImpl target;

    public CglibSomeServiceProxy(BaseProxyUsedServiceImpl target) {
        this.target = target;
    }

    public BaseProxyUsedServiceImpl createProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(BaseProxyUsedServiceImpl.class);
        enhancer.setCallback(this);
        return (BaseProxyUsedServiceImpl) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("目标对象方法执行之前");
        String msg = (String) method.invoke(target, objects[0]);
        System.out.println("目标对象方法执行之后");
        // 对代理对象的增强，将结果全转换为大写， 然后返回
        return msg.toUpperCase();
    }
}
